package com.study.juc.collection;

import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @program: juc-study
 * @author: jzhou
 * @date: 2022-08-25 14:36
 * @version: 1.0
 * @description: 多线程操作线程安全的集合
 **/
public class CollectionDemo {
	public static void main(String[] args) {
//		listDemo();
//		setDemo();
//		CopyOnWriteArraySet set = new CopyOnWriteArraySet();
		ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
		for (int i = 0; i < 30; i++) {
			int finalI = i;
			new Thread(() -> {
				map.put(finalI + "",UUID.randomUUID().toString().substring(0,8));
				System.out.println(map);
			},String.valueOf(i)).start();
		}

	}

	private static void setDemo() {
		CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
		for (int i = 0; i < 30; i++) {
			new Thread(() -> {
				set.add(UUID.randomUUID().toString().substring(0,8));
				System.out.println(set);
			},String.valueOf(i)).start();
		}
	}

	private static void listDemo() {
		CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
//		ArrayList<String> list = new ArrayList<>();
		for (int i = 0; i < 30; i++) {
			new Thread(() -> {
				list.add(UUID.randomUUID().toString().substring(0,8));
				System.out.println(list);
			},String.valueOf(i)).start();
		}
	}
}
